package javaMultiThreadInAction.chapter02;

import javaMultiThreadInAction.util.Tools;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description some description
 * @date 2024/1/10 10:04:32
 */
public class RaceConditionDemo {

    public static void main(String[] args) {
        // 客户端线程数
        int numberOfThreads = args.length > 0 ? Short.valueOf(args[0]) : Runtime
                .getRuntime().availableProcessors();
        Thread[] workerThreads = new Thread[numberOfThreads];
        for (int i = 0; i < numberOfThreads; i++) {
            workerThreads[i] = new WorkerThread(i, 10);
        }

        // 待所有线程创建完毕后，再一次性将其启动，以便这些线程能够尽可能地在同一时间内运行
        for (Thread ct : workerThreads) {
            ct.start();
        }
    }

    static class WorkerThread extends Thread {
        private final int requestCount;

        public WorkerThread(int id, int requestCount) {
            super("worker-" + id);
            this.requestCount = requestCount;
        }

        @Override
        public void run() {
            int i = requestCount;
            String requestID;

            RequestIDGenerator requestIDGenerator = RequestIDGenerator.getInstance();
            while (i-- > 0) {
                requestID = requestIDGenerator.nextID();
                processRequest(requestID);

            }
        }

        private void processRequest(String requestID) {
            // 模拟请求处理超时
            Tools.randomPause(50);
            System.out.printf("%s got requestId: %s %n", Thread.currentThread().getName(), requestID);
        }
    }
}
